// 用户合约操作接口类

// import blockChainApp from "../BlockChainApp"
const blockChainApp = require("../BlockChainApp")
const Message = require("../Message")
const Config = require("../Config")
const BlockChainApp = require("../BlockChainApp")

/**
 * 注册，创建一个区块链账户
 * @param: 个人信息参数
 * 
 * @return: 个人信息，区块链地址
 */

module.exports = {
    register: async function register(param){
        var accountAddr = await  blockChainApp.web3.eth.personal.newAccount(param.password)
        console.log("create super account: ", accountAddr, "; param:", param)
        // var defaultAccount = blockChainApp.web3.eth.defaultAccount;
        // var executeAccount = param.executeAccount
        var executeAccount = Config.executeAccount
        console.log("ddefault account: ", executeAccount)
        // 注册的用户数据存储到合约中
        var instance = await blockChainApp.contracts.User.deployed()
        var retData = null;
        await instance.createUser(param.username, accountAddr, param.telephone, param.email, param.identify, param.role, param.credentials, {from: executeAccount})
        .then((res)=>{
            retData = res;
        })
        .catch((err)=>{
            console.log("exception:", err)
            retData = Message.ERROR_CONSTANT()
        })
        console.log("register success: ", retData)
        return retData;      
    },

    /**
     * 系统管理员账号注册（只有一个）
     */
    registerSuperUser: async function registerSuperUser(param){
        var accountAddr = await  blockChainApp.web3.eth.personal.newAccount(param.password)
        console.log("create super account: ", accountAddr, "; param:", param)
        // var defaultAccount = blockChainApp.web3.eth.defaultAccount;
        // var executeAccount = param.executeAccount
        var executeAccount = Config.executeAccount
        console.log("ddefault account: ", executeAccount)
        // 注册的用户数据存储到合约中
        var instance = await blockChainApp.contracts.User.deployed()
        var retData = null;
        await instance.createSuperUser(param.username, accountAddr, param.telephone, param.email, param.identify, param.role, {from: executeAccount})
        .then((res)=>{
            retData = res;
        })
        .catch((err)=>{
            console.log("exception:", err)
            retData = Message.ERROR_CONSTANT()
        })
        console.log("register success: ", retData)
        return retData;        
    },

    /**
     * 登录，对应的就是解锁区块链账户进行交易.并返回账户信息
     */
    login: async function(param){
        var accountAddr = param.accountAddress;
        var executeAccount = Config.executeAccount;
        var password = param.password;
        // var instance = await blockChainApp.contracts.User.deployed()
        var retData = null;
        await blockChainApp.unlockAccount(accountAddr, password)
        .then(()=>{
            resData = true
        })
        .catch(err=>{
            console.log("exception: ", err)
            resData = Message.ERROR_CONSTANT()
        })
        return resData
    },

    loginByUsername: async function(param){
        var username = param.username;
        var password = param.password;
        var executeAccount = Config.executeAccount;
        var instance = await blockChainApp.contracts.User.deployed()
        var accountAddr = await instance.usernameAddress(username);       
        console.log("login address: ", accountAddr, password)
        if(accountAddr == "0x0000000000000000000000000000000000000000"){ // 用户不存在
            return Message.ERROR_CONSTANT()
        }
        // 解锁账户
        // blockChainApp.unlockAccount(accountAddr, password)
        // .then((data)=>{
        //     return data;
        // })
        // .catch(err=>{
        //     console.log("exception: ", err)
        //     return Message.ERROR_CONSTANT()
        // })
        // 用户未激活
        var state = await instance.getUserState.call(username);
        if(!state){
            return Message.ERROR_CONSTANT();
        }
        BlockChainApp.web3.eth.personal.unlockAccount(accountAddr, password, 600)
          .then(()=>{console.log("unlock success");return true;})
          .catch(err=>{console.log("unlock error:", err); return Message.ERROR_CONSTANT;})
    },

    /**
     * 退出，锁定区块链账户，无法执行交易
     */
    logout: async function logout(account){
        // var accountAddr = Config.executeAccount;
        var retData = null;
        await blockChainApp.lockAccount(account)
        .then(
            ()=>{
              retData = true  
            }
        )
        .catch(
            err=>{
                console.log("exception: ", err)
                retData = Message.ERROR_CONSTANT()
            }
        )
        return retData;
    },

    /**
     * 获取账户列表（需求权限，系统管理员）
     */
    userList: async function(){
        var res = []
        var userContarct = await blockChainApp.contracts.User.deployed()
        var count = userContarct.count()
    },

    /**
     * 更新用户信息
     */
    updateUser: async function(){
        
    },

    /**
     * 获取总用户数
     */
    totalUser: async function(){
        // console.log("total user: ", blockChainApp.contracts.User)
        var userContarct = await blockChainApp.contracts.User.deployed()
        return userContarct.count.call()
    },

    /**
     * 获取管理员用户数
     */
    totalAdminCount: async function(){
        var user = await blockChainApp.contracts.User.deployed();
        return user.adminCount.call()
    },

    /**
     * 获取用户角色
     */
    getUserRole: async function(_username){
        // console.log(blockChainApp.contracts.User)
        var userContarct = await blockChainApp.contracts.User.deployed()
        return userContarct.getUserRoleByUsername.call(_username)
    },

    /**
     * 检查用户是否拥有指定权限
     */
    validateUserRole: async function(_username, _roles){
        var userContarct = await blockChainApp.contracts.User.deployed()
        var role = await userContarct.getUserRoleByUsername.call(_username)
        for(var _role in _roles){
            if(role == _role)return true;
        }
        return false;
    },

    /**
     * 获取所有用户信息
     */
    getAllUser: async function(){
        var userContarct = await blockChainApp.contracts.User.deployed()
        var userinfos = await userContarct.getUserData.call()
        // console.log("userinfo: ", userinfos, userinfos.length)
        for(var i = 0; i < userinfos.length; i++){
            if(userinfos[i] == undefined)continue;
            // console.log("userinfo0: ", userinfos[i])
            userinfo = userinfos[i];
            userinfos[i].role = await userContarct.getUserRoleByUsername.call(userinfo.username);
            userinfos[i][5] = userinfos[i].role
            // console.log("userinfo: ", userinfos[i])
        }
        // console.log("")
        return userinfos;
    },

    // 激活用户
    activeUser: async function(username){
        var userContarct = await blockChainApp.contracts.User.deployed()
        userContarct.activeUser(username, {from: Config.executeAccount})
        .then(data=>{
            console.log("激活完成")
            return true;
        })
        .catch(err=>{
            console.log("激活错误：", err)
            return Message.ERROR_CONSTANT();
        })
    },

    // 更新用户权限
    updateUserRole: async function(accountAddress, role){
        var userContarct = await blockChainApp.contracts.User.deployed()
        userContarct.grantRoleToUser(accountAddress, role, {from: Config.executeAccount})
    }
}